# -*- encoding: utf-8 -*-
require 'digest/md5'
require 'multi_json'
require 'rest_client'

class Client
  
  def initialize(params, settings)
    @settings = settings
    @params = { # 淘宝参数
         app_key: @settings['api_key'].to_s,
          format: :json, 
               v: '2.0',
       timestamp: timestamp,
      partner_id: 'top-apitools'
    }
    @params.merge!(params.clone) unless params.empty? # 參數合併
    @params[:sign] = generate_sign(@settings['secret_key'], @params)
  end

  def get(url=@settings['rest_url'], count=0)
    format = if @params.has_key?(:method) && @settings['black_list'].include?(@params[:method]) # 淘寶接口格式限制
      :xml 
    else
      :json 
    end
    request = RestClient.get url, { params: @params }
    begin
      case format
      when :json
        @result = MultiJson.load(request)
      when :xml

      else
        html = request.force_encoding("GBK").encode("UTF-8")
        @result = Nokogiri::HTML(html)
      end
    rescue Exception => ex
      puts "========================参数========================"
      puts @params
      puts "========================错误：#{ex}========================"
      puts ex.message
      
       if count < 3 # 重试3次
         puts "========================开始重试========================"
         get(url, count+=1)
       else
         puts "========================很扯，三次都没搞定========================"
       end
    end
    parse(@result, generate_key(@params[:method]))
  end
  
  def parse(result, res_key) # 簡單解析一下
    return result unless result.is_a?(Hash)
    case
      when result.has_key?(res_key)
        result[res_key]
      when result.has_key?('error_response')
        result['error_response']['msg']
      else
        result
    end
  end
  
  private
  
    def generate_sign(secret, params={})
      rand = secret + params.sort.flatten.join
      Digest::MD5.hexdigest(rand).upcase! # 數字簽名
    end

    def generate_key(method) # 操作結果鍵
      method[7..-1].gsub(/\./, '_') + '_response' unless method.nil?
    end

    def root_key(method) # 獲取對象的鍵
      generate_key(method).split('_')[0] unless method.nil?
    end

    def timestamp # 时间戳
      Time.now.strftime("%Y-%m-%d %H:%M:%S")
    end
end